let layerIndex;

/**
 * 弹出学生新增/更新对话框
 */
function showStudentDlg(id) {
    let title = id ? "编辑" : "新增";
    $("#formId").css("display", "block");

    if (id) {
        // 编辑
        $.ajax({
            url: "/api/student/" + id,
            method: "GET"
        }).done(result => {
            console.log(result);
            if (result.code === 0 && result.data) {
                $.each(result.data, function (key, value) {
                    var field = $('#studForm [name="' + key + '"]');
                    if (field.length) {
                        if (field.is(':radio')) {
                            field.filter('[value="' + (value === 1 ? '1' : '0') + '"]').prop('checked', true);
                        } else if (field.is(':checkbox')) {
                            field.prop('checked', value === "yes");
                        } else {
                            field.val(value);
                        }
                    }
                });
            } else {
                alert("获取学生信息失败或学生不存在");
            }
        }).fail((jqXHR, textStatus, errorThrown) => {
            console.error("请求失败: " + textStatus + " - " + errorThrown);
            alert("获取学生信息失败，请重试");
        });

    } else {
        // 新增
        $("#studForm")[0].reset();
        $("#formId").css("display", "none");
    }

    layerIndex = layer.open({
        type: 1,
        title: title,
        area: ['520px', 'auto'],
        content: $('#studForm')
    });
}

/**
 * 获取搜索条件
 */
function getSearchCondition() {
    let formData = {};
    $('#queryForm').find('input,select').each(function () {
        let name = $(this).attr('name');
        let value = $(this).val();
        if (name && value) {
            formData[name] = value;
        }
    });
    return formData;
}

/**
 * 刷新表格
 * @param {number} currPage - 刷新后的页码，默认1（新增后跳转）
 */
function refreshTable(currPage = 1) {
    const table = layui.table;
    table.reload('tbStudent', {
        where: { data: getSearchCondition() },
        page: { curr: currPage }
    });
}

layui.use(function () {
    // 表单验证
    layui.form.on('submit(stud-dlg)', function (data) {
        event.preventDefault();
        commitStuDlg();
    });

    // 表格初始化
    const table = layui.table;
    let student = getSearchCondition();

    table.render({
        elem: '#tbStudent',
        url: '/api/student/getbypage',
        method: "POST",
        contentType: 'application/json',
        where: { "data": student },
        page: {
            layout: ['prev', 'page', 'next', 'limit', 'count'],
            limits: [10, 20, 30],
            limit: 10,
            groups: 3,
            first: '首页',
            last: '末页'
        },
        cols: [[
            { type: 'checkbox', fixed: 'left' },
            { field: 'id', fixed: 'left', width: 80, title: 'id', sort: true },
            { field: 'name', title: '姓名' },
            {
                field: 'sno',
                title: '学号',
                width: 150,
            },
            {
                field: 'sex',
                width: 80,
                title: '性别',
                sort: true,
                templet: d => d.sex === 1 ? '男' : (d.sex === 0 ? '女' : '未知'),
            },
            { field: 'age', width: 100, title: '年龄', sort: true },
            { field: 'right', width: 134, title: '操作', minWidth: 125, templet: '#editTemplate' }
        ]],
        done: function (rs) {
            // 表格渲染完成后的回调
        }
    });

    // 表格行工具事件
    table.on('tool(tbStudent)', function (obj) {
        var data = obj.data;
        if (obj.event === 'edit') {
            showStudentDlg(data.id);
        }
    });
});

/**
 * 搜索功能
 */
function search() {
    refreshTable(1); // 搜索后跳转到第一页
}

/**
 * 删除确认
 */
function deleteConfirm() {
    const table = layui.table;
    const checkStatus = table.checkStatus('tbStudent');
    const selectedData = checkStatus.data;

    if (selectedData.length === 0) {
        layer.alert("请先选择要删除的学生!");
        return;
    }

    const idsToDelete = selectedData.map(item => item.id);

    layer.confirm('您确定要删除选中的学生吗？此操作无法恢复！', { icon: 3, title: '警告' }, function (index) {
        $.ajax({
            url: "/api/student/delete",
            method: "DELETE",
            contentType: "application/json",
            data: JSON.stringify(idsToDelete),
            success: function (result) {
                if (result.code === 0) {
                    layer.msg("删除成功!");
                    refreshTable(); // 删除后刷新当前页
                } else {
                    layer.alert("删除失败: " + result.msg);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error("请求失败: ", jqXHR);
                layer.alert("请求失败，请稍后重试. 错误: " + errorThrown);
            }
        });

        layer.close(index);
    }, function () {
        layer.msg('已取消删除操作');
    });
}

/**
 * 提交新增/编辑对话框
 */
function commitStuDlg() {
    const table = layui.table;
    const $btnOK = $("#btnOK");
    $btnOK.prop("disabled", true).addClass("layui-btn-disabled");

    let id = $("#id").val();
    let formData = $("#studForm").serialize();

    function handleSuccess(message, isAdd) {
        layer.msg(message);
        refreshTable(isAdd ? 1 : undefined); // 新增跳转到第一页，编辑刷新当前页
        if (layerIndex) layer.close(layerIndex);
    }

    if (id) {
        // 更新学生
        $.ajax({
            url: "/api/student/update",
            method: "PUT",
            data: formData
        })
            .done(result => {
                if (result.code === 0) {
                    handleSuccess("更新成功", false);
                } else {
                    layer.alert("更新失败: " + result.msg);
                }
            })
            .fail((jqXHR, textStatus, errorThrown) => {
                console.error("更新失败:", errorThrown);
                layer.alert("更新失败，请重试");
            })
            .always(() => {
                $btnOK.prop("disabled", false).removeClass("layui-btn-disabled");
            });
    } else {
        // 新增学生
        $.ajax({
            url: "/api/student/add",
            method: "POST",
            data: formData
        })
            .done(result => {
                if (result.code === 0) {
                    handleSuccess("添加成功", true);
                } else {
                    layer.alert("添加失败: " + result.msg);
                }
            })
            .fail((jqXHR, textStatus, errorThrown) => {
                console.error("添加失败:", errorThrown);
                layer.alert("添加失败，请重试");
            })
            .always(() => {
                $btnOK.prop("disabled", false).removeClass("layui-btn-disabled");
            });
    }
}